package com.example.yunxinagyue.info_user

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DatePickerDialog
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import com.example.yunxinagyue.Logger
import com.example.yunxinagyue.R
import java.io.*
import java.util.*

const val NAME:String="name"
var user=User("","","","","","")
data class User(
    var name:String?,
    var gender:String?,
    var birthday:String?,
    var region:String?,
    var university:String?,
    var introductory:String?
):Serializable {
    override fun toString(): String {
        return user.gender.toString()+user.name.toString()+user.university.toString()+user.introductory.toString()
    }
}
class UserInfo : AppCompatActivity(), View.OnClickListener {
    val path:String=Environment.getExternalStorageDirectory().absolutePath.toString()+"/data.txt"
    private var name: TextView? = null
    private var intro: TextView? = null
    private var university: TextView? = null
    private var born: TextView? = null
    private var spinnerGender: Spinner? = null
    private var imagePhoto: ImageView? = null

    private var nameLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val u=result.data?.getStringExtra(NAME)
            Logger.info(TAG, "nameLauncher get result = $u")
            name!!.text=u.toString()
            user.name=u.toString()
        } else {
            Logger.error(TAG, "error when launch activity: $result")
        }
    }
    private var universityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val u=result.data?.getStringExtra("university")
            Logger.info(TAG, "universityLauncher get result = $u")
            university!!.text=u.toString()
            user.university=u.toString()
        } else {
            Logger.error(TAG, "error when launch activity: $result")
        }
    }
    private var introLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val u=result.data?.getStringExtra("intro")
            Logger.info(TAG, "introLauncher get result = $u")
            intro!!.text=u.toString()
            user.introductory=u.toString()
        } else {
            Logger.error(TAG, "error when launch activity: $result")
        }
    }
    private var bornLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val u=result.data?.getStringExtra(NAME)
            Logger.info(TAG, "nameLauncher get result = $u")
            born!!.text=u.toString()
            user.name=u.toString()
        } else {
            Logger.error(TAG, "error when launch activity: $result")
        }
    }
    private var spinnerGenderLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val u=result.data?.getStringExtra(NAME)
            Logger.info(TAG, "nameLauncher get result = $u")
            name?.text=u.toString()
            user.name=u.toString()
        } else {
            Logger.error(TAG, "error when launch activity: $result")
        }
    }
    private val pickImageLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        // 处理选择的图片
        uri?.let {
            imagePhoto!!.setImageURI(it)
        } ?: Logger.error(TAG, "return uri is null")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)
        name = findViewById(R.id.name)
        intro = findViewById(R.id.intro)
        university = findViewById(R.id.university)
        born = findViewById(R.id.born)
        spinnerGender = findViewById(R.id.spinner_gender)
        imagePhoto = findViewById(R.id.photo)
        user = loadData() ?: User("", "", "", "", "", "")
        Logger.debug(TAG, "get user: $user")
        name!!.text = user.name
        intro!!.text = user.introductory
        university!!.text = user.university
        born!!.text = user.birthday
        spinnerGender!!.tag = user.gender
        val actionBar = supportActionBar
        if (actionBar != null) {
//            设置ActionBar是否显示返回键
            actionBar.setDisplayHomeAsUpEnabled(true)
//            导入返回键图片
            actionBar.setHomeAsUpIndicator(R.drawable.ic_return)
//            设置是否显示标题
            actionBar.setDisplayShowTitleEnabled(true)
            actionBar.title = "编辑我的资料"
        }
        name?.setOnClickListener(this)
        born?.setOnClickListener(this)
        intro?.setOnClickListener(this)
        university?.setOnClickListener(this)
        imagePhoto?.setOnClickListener(this)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            android.R.id.home ->
            {
                saveData()
                finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onClick(p0: View?) {
        val spinnerGender = findViewById<Spinner>(R.id.spinner_gender)
        when(p0?.id){
            R.id.name -> {
                val intent=Intent(this,RectifyName::class.java)
                nameLauncher.launch(intent)
            }
            R.id.born -> {
                showDatePickerDialog(this,born!!)
            }
            R.id.university -> {
                val intent=Intent(this,UniversityActivity::class.java)
                universityLauncher.launch(intent)
            }
            R.id.intro -> {
                val intent=Intent(this,RectifyIntro::class.java)
                introLauncher.launch(intent)
            }
            R.id.photo-> {
                //访问相册
                pickImageLauncher.launch("image/*")
            }
            R.id.spinner_gender -> {
                spinnerGender.adapter = ArrayAdapter(this,android.R.layout.simple_spinner_item, arrayOf("男","女"))
                user.gender= spinnerGender.selectedItem.toString()

            }
        }
    }



    //进行外部存储
    private fun saveData(){
       try {
           //        使用外部存储将序列化后的对象存储在根目录下的user_info下
           val file = File(Environment.getExternalStorageDirectory().absolutePath)
           if(!file.exists()){
               file.mkdir()
           }
           val newFile = File(Environment.getExternalStorageDirectory().absolutePath,"/ser_info.txt")
           if(!newFile.exists()){
               newFile.createNewFile()
           }
           val fos=ObjectOutputStream(FileOutputStream(newFile))
           fos.writeObject(user)
           fos.flush()
           fos.close()
       }catch (e:Exception){
           e.printStackTrace()
       }

    }

    private fun loadData(): User? {
        return try {
            val file=File(Environment.getExternalStorageDirectory().absolutePath,"/ser_info.txt")
            val fos=ObjectInputStream(FileInputStream(file))
            val obj=fos.readObject() as User
            fos.close()
            obj
        }catch (e:Exception){
            e.printStackTrace()
            null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        saveData()
    }

    //显示 日期选择器
    private var calendar = Calendar.getInstance(Locale.CHINA)
    private  val themeResId = 3//0是日历图1是滚轴
    /**
     * 日期选择
     * @param activity
     * @param born
     */
    @SuppressLint("SetTextI18n")
    fun showDatePickerDialog(
        activity: UserInfo,
        born: TextView
    ) {
        calendar = Calendar.getInstance(Locale.CHINA)
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        DatePickerDialog(
            activity, themeResId,
            { _, year, monthOfYear, dayOfMonth ->
                // 绑定监听器(How the parent is notified that the date is set.)
                // 此处得到选择的时间，可以进行你想要的操作
                born.text = "$year"+"年"+"$monthOfYear"+"月"+"$dayOfMonth"+"日"
                user.birthday="$year"+"年"+"$monthOfYear"+"月"+"$dayOfMonth"+"日"

            } // 设置初始日期
            , calendar.get(Calendar.YEAR)
            , calendar.get(Calendar.MONTH)
            , calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    companion object {
        private const val TAG = "UserInfo"
    }

}

